<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="state.goodForm" :rules="state.rules" ref="goodRef" label-width="100px" class="goodForm">
        <el-form-item label="商品分类">
          <el-select v-model="state.categoryId" class="m-2" placeholder="Select" size="large">
            <el-option v-for="item in state.category" :key="index" :label="item.categoryName" :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input style="width: 300px" v-model="state.goodForm.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input style="width: 300px" type="textarea" v-model="state.goodForm.goodsIntro"
            placeholder="请输入商品简介(100字)"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="originalPrice">
          <el-input type="number" min="0" style="width: 300px" v-model="state.goodForm.originalPrice"
            placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品售卖价" prop="sellingPrice">
          <el-input type="number" min="0" style="width: 300px" v-model="state.goodForm.sellingPrice"
            placeholder="请输入商品售价"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stockNum">
          <el-input type="number" min="0" style="width: 300px" v-model="state.goodForm.stockNum"
            placeholder="请输入商品库存"></el-input>
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-input style="width: 300px" v-model="state.goodForm.tag" placeholder="请输入商品小标签"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="goodsSellStatus">
          <el-radio-group v-model="state.goodForm.goodsSellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="商品主图" prop="goodsCoverImg">
          <el-upload class="avatar-uploader" action="http://localhost:8080/goods/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="state.goodForm.goodsCoverImg" :src="state.goodForm.goodsCoverImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ state.id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from 'axios'
import { ElMessage, UploadProps } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const editor = ref(null)
const goodRef = ref(null)
const route = useRoute()
const router = useRouter()
const { id } = route.query
const state = reactive({
  id: id,
  goodForm: {
    goodsName: '',
    goodsIntro: '',
    originalPrice: '',
    sellingPrice: '',
    stockNum: '',
    goodsSellStatus: '0',
    goodsCoverImg: '',
    tag: ''
  },
  categoryId: '',
  category: [],
  rules: {
    goodsSelect: [
      { required: 'true', message: '请选择商品分类', trigger: ['change'] }
    ],
    goodsName: [
      { required: 'true', message: '请填写商品名称', trigger: ['change'] }
    ],
    originalPrice: [
      { required: 'true', message: '请填写商品价格', trigger: ['change'] }
    ],
    sellingPrice: [
      { required: 'true', message: '请填写商品售价', trigger: ['change'] }
    ],
    stockNum: [
      { required: 'true', message: '请填写商品库存', trigger: ['change'] }
    ],
  },

})

let instance
onMounted(() => {
  axios.post('http://localhost:8080/goods/searchCategory').then(res => {
    state.category = res.data
  })
  //   接下来一系列代码都是在修改 WangEditor 编辑器的配置：
  // showLinkImg、showLinkImgAlt、showLinkImgHref 控制是否显示插入链接的输入框。
  // uploadImgMaxSize 设置图片上传的最大大小限制。
  // uploadFileName 控制图片上传表单文件域的 name 属性。
  // uploadImgHeaders 设置图片上传请求的 header。
  // uploadImgHooks 是关于图片上传后的回调函数，customInsert 是其中的一个钩子函数，用于在图片上传后把图片自定义地插入到编辑器中去。
  // uploadImgServer 是设置图片上传的服务端地址。
  // onchange 是 WangEditor 编辑器的一个事件处理函数，在编辑器内容发生变化时会触发。这里只是简单地输出一段日志。
  // 最后一行是创建 WangEditor 编辑器实例并完成初始化。create() 方法负责完成所有必要的 DOM 元素的创建和清空，并且在编辑器的插件和配置都加载完成后，会触发 ready 事件。
  instance = new WangEditor(editor.value)
  instance.config.showLinkImg = false
  instance.config.showLinkImgAlt = false
  instance.config.showLinkImgHref = false
  instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
  instance.config.uploadFileName = 'file'
  instance.config.uploadImgHeaders = {
  }
  // 图片返回格式不同，需要自定义返回格式
  instance.config.uploadImgHooks = {
    // 图片上传并返回了结果，想要自己把图片插入到编辑器中
    // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
    customInsert: function (insertImgFn, result) {
      console.log('result', result.data)
      // result 即服务端返回的接口
      // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
      if (result.data != null || result.data != "") {
        insertImgFn(result.data)
      }
    }
  }
  // 这段代码的作用是将 instance.config.uploadImgServer 设置为 http://localhost:8080/goods/upload2，
  // 并在 instance.config 对象上添加一个 onchange 方法，当对象的值改变时会触发该方法，输出字符串 change。
  // Object.assign 方法用于将一个或多个源对象的所有可枚举属性（包括 Symbol 类型的属性）复制到目标对象中，该方法在这里将 onchange 方法添加到了 instance.config 对象中。
  instance.config.uploadImgServer = 'http://localhost:8080/goods/upload2'
  Object.assign(instance.config, {
    onchange() {
      console.log('change')
    },
  })
  instance.create()
  if (id) {
    axios.post(`http://localhost:8080/goods/searchGoodsDetail/${id}`).then(res => {
      const goods = res.data
      console.log(goods.goodsCoverImg);
      state.goodForm = {
        goodsName: goods.goodsName,
        goodsIntro: goods.goodsIntro,
        originalPrice: goods.originalPrice,
        sellingPrice: goods.sellingPrice,
        stockNum: goods.stockNum,
        goodsSellStatus: String(goods.goodsSellStatus),
        goodsCoverImg: goods.goodsCoverImg,
        tag: goods.tag
      }
      state.categoryId = goods.goodsCategoryId
      if (instance) {
        // 初始化商品详情 html
        instance.txt.html(goods.goodsDetailContent)
      }
    })
  }
})
onBeforeUnmount(() => {
  instance.destroy()
  instance = null
})
/* 提交 */
const submitAdd = () => {
  goodRef.value.validate((vaild) => {
    if (vaild) {
      // 默认新增用 post 方法
      let httpOption = axios.post
      let params = {
        goodsCategoryId: state.categoryId,
        goodsCoverImg: state.goodForm.goodsCoverImg,
        goodsDetailContent: instance.txt.html(),
        goodsIntro: state.goodForm.goodsIntro,
        goodsName: state.goodForm.goodsName,
        goodsSellStatus: state.goodForm.goodsSellStatus,
        originalPrice: state.goodForm.originalPrice,
        sellingPrice: state.goodForm.sellingPrice,
        stockNum: state.goodForm.stockNum,
        tag: state.goodForm.tag
      }
      console.log('params', params)
      if (id) {
        console.log("id:" + id);
        params.goodsId = id
        // 修改商品使用 put 方法
        httpOption = axios.put
      }
      httpOption('http://localhost:8080/goods/opera', params).then(() => {
        ElMessage.success(id ? '修改成功' : '添加成功')
        router.push({ path: '/admin/goods' })
      })
    }
  })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  state.goodForm.goodsCoverImg = URL.createObjectURL(uploadFile.raw!)
  state.goodForm.goodsCoverImg = response
  console.log(response);
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('必须是jpeg文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 98px;
  height: 98px;
  display: block;
}

.add {
  display: flex;
}

.add-container {
  flex: 1;
  height: 100%;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 98px;
  height: 98px;
  text-align: center;
}
</style>